/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.uia.entity.SysAppParameterTemplate;
import com.hsxxherp.key.uia.entity.SysAppParameterTemplateVersion;
import com.hsxxherp.key.uia.mapper.SysAppParameterTemplateMapper;
import com.hsxxherp.key.uia.mapper.SysAppParameterTemplateVersionMapper;
import com.hsxxherp.key.uia.service.ISysAppParameterTemplateVersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.OffsetDateTime;
import java.util.UUID;

@Service
public class SysAppParameterTemplateVersionServiceImpl extends ServiceImpl<SysAppParameterTemplateVersionMapper, SysAppParameterTemplateVersion>
        implements ISysAppParameterTemplateVersionService {

    private static final Logger logger = LoggerFactory.getLogger(SysAppParameterTemplateVersionServiceImpl.class);

    @Autowired
    private SysAppParameterTemplateMapper sysAppParameterTemplateMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppParameterTemplateVersion createDefaultTemplateVersion(String templateId) {
        SysAppParameterTemplateVersion templateVersion = new SysAppParameterTemplateVersion();
        templateVersion.setTemplateId(templateId);
        templateVersion.setVersionNumber("1.0.0");
        templateVersion.setReleaseDate(OffsetDateTime.now());
        templateVersion.setVersionDescription("默认模板版本");
        templateVersion.setStatus(SysAppParameterTemplateVersion.Status.PUBLISHED);
        templateVersion.setSortOrder(1);

        boolean success = super.save(templateVersion);
        if (success) {
            logger.info("成功创建默认模板版本，模板版本 ID: {}", templateVersion.getTemplateVersionId());
            return templateVersion;
        }
        logger.error("创建默认模板版本失败，模板 ID: {}", templateId);
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppParameterTemplateVersion createParameterTemplateVersion(SysAppParameterTemplateVersion templateVersion) {
        // 参数校验
        if (templateVersion == null) {
            logger.error("创建参数模板版本时，传入的模板版本对象为 null");
            return null;
        }
        if (templateVersion.getTemplateId() == null || templateVersion.getTemplateId().isEmpty()) {
            logger.error("创建参数模板版本时，模板 ID 为空");
            return null;
        }
        if (templateVersion.getVersionNumber() == null || templateVersion.getVersionNumber().isEmpty()) {
            logger.error("创建参数模板版本时，版本号为空");
            return null;
        }

        // 检查关联的模板是否存在
        SysAppParameterTemplate template = sysAppParameterTemplateMapper.selectById(templateVersion.getTemplateId());
        if (template == null) {
            logger.error("创建参数模板版本时，关联的模板 ID {} 不存在", templateVersion.getTemplateId());
            return null;
        }

        // 检查版本号是否已存在
        QueryWrapper<SysAppParameterTemplateVersion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_id", templateVersion.getTemplateId())
                .eq("version_number", templateVersion.getVersionNumber());
        if (count(queryWrapper) > 0) {
            logger.error("创建参数模板版本时，模板 ID {} 下版本号 {} 已存在", templateVersion.getTemplateId(), templateVersion.getVersionNumber());
            return null;
        }

        // 设置默认值
        templateVersion.setTemplateVersionId(UUID.randomUUID().toString());
        templateVersion.setReleaseDate(OffsetDateTime.now());
        if (templateVersion.getStatus() == null) {
            templateVersion.setStatus(SysAppParameterTemplateVersion.Status.UNPUBLISHED);
        }
        if (templateVersion.getSortOrder() == null) {
            templateVersion.setSortOrder(1);
        }

        // 保存模板版本
        boolean success = save(templateVersion);
        if (success) {
            logger.info("成功创建参数模板版本，模板版本 ID: {}", templateVersion.getTemplateVersionId());
            return templateVersion;
        } else {
            logger.error("创建参数模板版本失败，模板 ID: {}", templateVersion.getTemplateId());
            return null;
        }
    }
}